//
//  RootViewController.m
//  豆瓣HW
//
//  Created by dllo on 15/11/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RootViewController.h"
#import "ActivityTableViewCell.h"
#import "DetailActivityViewController.h"
#import "JSONKit.h"
#import "Activity.h"
#import "UIImageView+WebCache.h"

@interface RootViewController ()<UITableViewDataSource, UITableViewDelegate>

//@property (nonatomic, retain) NSMutableDictionary *ActDic;
@property (nonatomic, retain) UITableView *tableV;
@property (nonatomic, retain) NSMutableArray *ActArr;

@end

@implementation RootViewController

- (void)dealloc
{
    [_ActArr release];
//    [_ActDic release];
    [_tableV release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"活动";
    
    [self getData];
    
    self.tableV = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    [_tableV release];
    
//    // 将ActArr存到本地
//    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *filePath = [path stringByAppendingPathComponent:@"arr.xml"];
//    [self.ActArr writeToFile:filePath atomically:YES];
//    NSLog(@"%@", NSHomeDirectory());
//    NSArray *getArr = [NSArray arrayWithContentsOfFile:filePath];
//    NSLog(@"%@", getArr);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    while (self.ActArr.count == 0) {
        [self.tableV reloadData];
    }
}


// 网络编程
- (void)getData
{
    
    NSURL *url = [NSURL URLWithString:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionDataTask *getTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.ActArr = [NSMutableArray array];
        NSMutableArray *arr = [dic objectForKey:@"events"];
        for (NSMutableDictionary *tempDic in arr) {
            
            Activity *act = [[Activity alloc] init];
            [act setValuesForKeysWithDictionary:tempDic];
            
            NSString *urlStr = act.image;
            
            NSString *urlEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            NSURL *url = [NSURL URLWithString:urlEncode];
            
            NSURLSession *session = [NSURLSession sharedSession];
            NSURLSessionDownloadTask *downImageT = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
                
                NSString *cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                //         拼接文件名 - 推荐用系统推荐的文件名(与服务器文件同名), 也可自定义文件名
                //         自定义文件名
                //                NSString *file = [cach stringByAppendingPathComponent:@"wangning.png"];
                
                // 系统推荐文件名
                NSString *file = [cach stringByAppendingPathComponent:response.suggestedFilename];
                
                // 管理文件的类
                NSFileManager *fileM = [NSFileManager defaultManager];
                
                // 将下载数据有临时文件搬到自己的缓存路径内
                [fileM moveItemAtPath:location.path toPath:file error:nil];
                
                act.finalImage = [UIImage imageWithContentsOfFile:file];
                
            }];
            
            [downImageT resume];
            
            
            [self.ActArr addObject:act];
            [act release];
        }
        
        
        [self.tableV reloadData];
        
    }];
    
    [getTask resume];
    
//        NSString *urlStr = act.image;
//
//        NSString *urlEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//
//        NSURL *url = [NSURL URLWithString:urlEncode];
//
//        NSURLSession *session = [NSURLSession sharedSession];
//        NSURLSessionDownloadTask *downImageT = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
//    
//            NSString *cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//    
//    //         拼接文件名 - 推荐用系统推荐的文件名(与服务器文件同名), 也可自定义文件名
//    //         自定义文件名
//    //                NSString *file = [cach stringByAppendingPathComponent:@"wangning.png"];
//    
//            // 系统推荐文件名
//            NSString *file = [cach stringByAppendingPathComponent:response.suggestedFilename];
//    
//            // 管理文件的类
//            NSFileManager *fileM = [NSFileManager defaultManager];
//    
//            // 将下载数据有临时文件搬到自己的缓存路径内
//            [fileM moveItemAtPath:location.path toPath:file error:nil];
//    
//            cell.imageV6.image = [UIImage imageWithContentsOfFile:file];
//            
//        }];
//        
//        [downImageT resume];
    
}

// 数据解析
//- (void)getData
//{
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"activitylist" ofType:@"txt"];
//    NSData *data = [NSData dataWithContentsOfFile:filePath];
//    
//    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
////    NSMutableDictionary *dic = [data objectFromJSONData];
//
//    self.ActArr = [NSMutableArray array];
////    for (NSString *key in [dic objectForKey:@"events"]) {
////        
////        NSMutableArray *arr = [NSMutableArray array];
////            for (NSMutableDictionary *tempDic in [dic objectForKey:key]) {
////                Activity *act = [[Activity alloc] init];
////                [act setValuesForKeysWithDictionary:tempDic];
////                [arr addObject:act];
////                [act release];
////            }
////
////        [self.ActDic setValue:arr forKey:key];
////    }
//    NSMutableArray *arr = [dic objectForKey:@"events"];
//    for (NSMutableDictionary *tempDic in arr) {
//        
//        Activity *act = [[Activity alloc] init];
//        [act setValuesForKeysWithDictionary:tempDic];
//        [self.ActArr addObject:act];
//        [act release];
//    }
//    
//}

// 选中行操作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailActivityViewController *detailActivityVC = [[DetailActivityViewController alloc] init];
    detailActivityVC.act = [self.ActArr objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:detailActivityVC animated:YES];
    [detailActivityVC release];
    
}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 3;
}
// 每个区有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return 20;
    return self.ActArr.count;
}

// 铺建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    ActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (nil == cell) {
        cell = [[[ActivityTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellStr] autorelease];
    }
//    NSString *key  = [self.ActDic.allKeys objectAtIndex:indexPath.section];
//    NSMutableArray *arr = [self.ActDic objectForKey:key];
//    NSMutableDictionary *dic = [self.ActArr objectAtIndex:indexPath.section];
//    NSString *key = [dic.allKeys objectAtIndex:indexPath.row];
//    NSMutableArray *arr = [dic objectForKey:key];
    
    
    Activity *act = [self.ActArr objectAtIndex:indexPath.row];

    cell.lable4.text = act.address;
    cell.lable5.text = act.category_name;
    NSString *str1 = [NSString stringWithFormat:@"%ld", act.wisher_count];
    cell.lable6.text = str1;
    NSString *str2 = [NSString stringWithFormat:@"%ld", act.participant_count];
    cell.lable7.text = str2;
    cell.lable8.text = act.title;
    NSRange range = {5, 11};
    //    NSString *time = [stu.begin_time substringFromIndex:5];
    NSString *time = [act.begin_time substringWithRange:range];
    
    NSString *time1 = [act.end_time substringWithRange:range];
    NSString *time2 = [time stringByAppendingString:@" -- "];
    NSString *time3 = [time2 stringByAppendingString:time1];
    cell.lable3.text = time3;
    cell.imageV6.image = act.finalImage;

    return cell;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
